import type { EChartsOption } from "echarts";
import { computed, nextTick, reactive, ref, Ref, unref, watch } from "vue";
import AutoPlay from "./autoPlay";
import echarts from "./echarts";

//  传入DIV实例
export const useECharts = (elRef: Ref<HTMLDivElement>) => {
  let player: any = null;
  let chartInstance: echarts.ECharts | null = null;
  const cacheOptions = ref({}) as Ref<EChartsOption>;
  const resize = () => {
    chartInstance?.resize({
      animation: {
        duration: 300,
        easing: "quadraticIn",
      },
    });
  };
  const div = reactive({
    clientWidth: 0,
    clientHeight: 0,
  });
  const getOptions = computed(() => {
    return {
      ...cacheOptions.value,
    } as EChartsOption;
  });

  const initCharts = () => {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }
    chartInstance = echarts.init(el);
    // 获取div宽高变化
    const callback = function (mutationsList: any, observer: any) {
      div.clientWidth = elRef.value.offsetWidth;
      div.clientHeight = elRef.value.offsetHeight;
    };
    const observer = new MutationObserver(callback);
    const config = { attributes: true, childList: true, subtree: true };
    observer.observe(el, config);
  };
  // 监听盒子宽高变化,重绘图形
  watch(
    () => div,
    () => {
      nextTick(() => {
        resize();
      });
    },
    {
      deep: true,
    }
  );

  //  设置参数
  const setOptions = (options: EChartsOption, clear = true) => {
    cacheOptions.value = options;
    nextTick(() => {
      if (!chartInstance) {
        initCharts();
        if (!chartInstance) return;
      }
      //  清空当前实例，移除实例中所有的组件和图表。9
      clear && chartInstance?.clear();
      //  重新渲染数据
      chartInstance?.setOption(unref(cacheOptions.value));
      if (!player) {
        player = new AutoPlay(chartInstance);
        player.init();
      } else {
        player.init(0);
      }
    });
  };
  return {
    setOptions,
  };
};
